package com.dt.app.controller.account;

import com.dt.app.common.constant.ConstantCode;
import com.dt.app.common.service.RedisService;
import com.dt.app.common.utils.VerifyCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author DT
 * @date 2021/6/8 22:09
 */
@Api(tags = "系统验证码API")
@RestController
@RequestMapping("api/v1/verification")
public class VerificationController {

    private final RedisService redisService;

    public VerificationController(RedisService redisService) {
        this.redisService = redisService;
    }

    @GetMapping("getCode")
    @ApiOperation(value = "获取验证码接口")
    public void getCode(HttpServletResponse response) throws IOException {
        // 禁止缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        // 设置响应格式为png图片
        response.setContentType("image/png");
        // 生成图片验证码
        BufferedImage image = new BufferedImage(ConstantCode.WIDTH, ConstantCode.HEIGHT, BufferedImage.TYPE_INT_RGB);
        String randomText = VerifyCodeUtils.drawRandomText(image,ConstantCode.WIDTH,ConstantCode.HEIGHT);
        // 存入redis
        redisService.set(ConstantCode.KAPTCHA_KEY, randomText, ConstantCode.KAPTCHA_EXP_TIME);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, ConstantCode.IMG_JPG, out);
        out.flush();
        out.close();
    }
}
